package com.weixing.mall.core.handler;

import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;


/**
 * Description:全局参数绑定异常处理器 <br/>
 *
 * @param:
 * @return:
 * @Author: kfc
 * @Date: 2019/8/2 15:43
 */
@ControllerAdvice
public class BindingExceptionHandler {

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result handleBindException(BindException ex) {
        // ex.getFieldError():随机返回一个对象属性的异常信息。如果要一次性返回所有对象属性异常信息，则调用ex.getAllErrors()
        FieldError fieldError = ex.getFieldError();
        return ResultUtil.error(fieldError.getDefaultMessage());
    }


    /**
     * 方法参数校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public Result constraintViolationException(Exception e) {
        if (e.getMessage() != null) {
            int index = e.getMessage().indexOf(":");
            return ResultUtil.error(index != -1 ?
                    e.getMessage().substring(index + 1).trim() : e.getMessage());
        }
        return ResultUtil.error("参数校验不合法");
    }
}
